﻿using System.Threading.Tasks;
using Typesense;

namespace SearchService.Data;

public static class SearchInitializer
{
    public static async Task EnsureIndexExists(ITypesenseClient client)
    {
        const string schemaName = "questions";
        try
        {
            await client.RetrieveCollection(schemaName);
            Console.WriteLine($"Collection {schemaName} already exists.");
            return;
        }
        catch (TypesenseApiNotFoundException)
        {
            Console.WriteLine($"Collection {schemaName} has not been created yet.");
        }

        var schema = new Schema(
            schemaName,
            [
                new("id", FieldType.Int64),
                new("title", FieldType.String, locale: "zh"),
                new("content", FieldType.String, locale: "zh"),
                new("tags", FieldType.StringArray, locale: "zh"),
                new("createdAt", FieldType.Int64),
                new("hasAcceptedAnswer", FieldType.Bool),
                new("answerCount", FieldType.Int32),
            ]
        )
        {
            DefaultSortingField = "createdAt",
        };

        await client.CreateCollection(schema);
        Console.WriteLine($"Collection {schemaName} has been created.");
    }
}
